import React, { useState, useEffect } from 'react';
import { message, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { connect, Dispatch } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import { DICT_LIST, DICT_ADD, DICT_UPDATE, DICT_UNMOUNT } from '@/actions/dict';
import AGrid, { AGridButtonCallBackModel } from '@/components/SelfComp/AGrid';
import { ConnectState } from '@/models/connect';
import { DictItem } from '@/types/dict';
import { DataItem, FlagEnum } from '@/types/global';
import { getItemValue } from '@/utils/commons';
import DictQueryForm from './components/DictQueryForm';
import AddDictModal from './components/AddDictModal';
import UpdateDictModal from './components/UpdateDictModal';

interface DictListProps {
  dispatch: Dispatch;
  dictList: DictItem[],
  total: number,
  loading: boolean;
  pageSize: number;
  addLoading: boolean;
  updateLoading: boolean;
  editFlagData: DataItem[];
  statusData: DataItem[];
}

const EMPTY: DictItem = {
  dictId: '',
  dictName: '',
  dictDesc: '',
  dictItemName: '',
  dictItemDesc: '',
  status: '',
  editFlag: '',
}

const DictList: React.FC<DictListProps> = (props) => {
  // 新增弹窗
  const [addModalVisible, setAddModalVisible] = useState<boolean>(false);
  const [dictFormData, setDictFormData] = useState<DictItem>(EMPTY);
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const [selectedRows, setSelectedRows] = useState<DictItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [queryParam, setQueryParam] = useState<DictItem>();
  // 默认为10
  const [pageSize, setPageSize] = useState<number>(10);
  const [flag, setFlag] = useState<FlagEnum>('edit');

  useEffect(() => {
    console.info('DictList.useEffect');
    const { dispatch } = props;
    return () => {
      dispatch(DICT_UNMOUNT({}));
    }
  }, []);

  const columns: ColumnsType<DictItem> = [
    {
      title: '字典名',
      dataIndex: 'dictName',
      // width: 150
    },
    {
      title: '字典描述',
      dataIndex: 'dictDesc',
      // width: 150
    },
    {
      title: '字典项',
      dataIndex: 'dictItemName',
      // width: 150
    },
    {
      title: '字典项描述',
      dataIndex: 'dictItemDesc',
      // width: 150
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text: string, record: DictItem, index: number) => dictStatusFunc(record),
      // width: 70
    },
    {
      title: '是否可编辑',
      dataIndex: 'editFlag',
      // width: 70
    }
  ];

  const dictStatusFunc = (record: DictItem) => {
    const { statusData } = props;
    const { status } = record;
    const value = getItemValue(statusData, status);
    return <Tag color='processing'>{value}</Tag>
  }

  /**
   * 查询满足条件的数据字典
   */
  const handleSubmitEx = (record: DictItem) => {
    console.info('DictList.handleSubmitEx');
    console.info(record);
    const queryParam = {
      ...record
    };
    // 查询条件保存起来，方便点击页码时使用
    // setState回调方法，保证先更新state
    setQueryParam(queryParam);
    fetchAllDict(1, pageSize, queryParam);
  }

  const handleReset = () => {
    // 是否清空表格
  }

  const openAddDictModal = () => {
    // console.info('openAddDictModal');
    // console.info(records);
    if (selectedRowKeys && selectedRowKeys.length == 1) {
      const row = selectedRows[0];
      setDictFormData(row);
    }
    setAddModalVisible(true);
  }

  const handleAddModalOk = async (record: DictItem) => {
    console.log(record);
    const { dispatch } = props;
    const res = await dispatch(DICT_ADD(record));
    console.info(res);
    if (res) {
      setDictFormData(EMPTY);
      setAddModalVisible(false);
      fetchAllDict(1, pageSize, queryParam);
    }
  }

  const handleAddModalCancel = () => {
    setDictFormData(EMPTY);
    setAddModalVisible(false);
  };

  const openUpdateDictModal = (record: DictItem[], flag: FlagEnum) => {
    // 表格选中内容
    console.info('openUpdateDictModal');
    console.info(record);
    const row = record[0];
    const dictFormData = {
      ...row,
    };
    setDictFormData(dictFormData);
    setFlag(flag);
    setUpdateModalVisible(true);
  }

  /**
   * 更新面板的确定事件
   * @param {*} record 更新表单
   */
  const handleUpdateModalOk = async (record: DictItem) => {
    // console.log('handleUpdateModalOk');
    // console.log(record);
    // console.info(dictFormData);
    if (flag === 'edit') {
      const { dispatch } = props;
      const res = await dispatch(DICT_UPDATE(record));
      console.info(res);
      if (res) {
        setDictFormData(EMPTY);
        setUpdateModalVisible(false);
        fetchAllDict(1, pageSize, queryParam);
      }
    } else {
      setDictFormData(EMPTY);
      setUpdateModalVisible(false);
    }
  }

  const handleUpdateModalCancel = () => {
    setDictFormData(EMPTY);
    setUpdateModalVisible(false);
  };

  /**
   * 分页查询系统参数信息
   * @param {*} pageNum 页码
   * @param {*} pageSize 每页记录条数
   */
  const fetchAllDict = (pageNum: number, pageSize: number, queryParam?: DictItem) => {
    const { dispatch } = props;
    dispatch(DICT_LIST({
      ...queryParam,
      pageSize,
      pageNum
    }));
  }

  /**
   * 处理按钮点击回调事件
   * @param {*} payload 数据包
   */
  const handleBtnCallBack = (callBackModel: AGridButtonCallBackModel<DictItem>) => {
    console.log('handleBtnCallBack');
    console.log(callBackModel);
    // btn 按钮
    // keys 表格勾选数组
    const { code, keys } = callBackModel;
    // 新增
    if (code === 'add') {
      if (keys && keys.length > 1) {
        message.warn('新增时最多只允许选择一条数据当父节点！');
        return;
      }
      // 选中一条，可以将字典名当父节点使用
      openAddDictModal();
      return;
    }
    // 修改
    if (code === 'edit') {
      const { rows } = callBackModel;
      openUpdateDictModal(rows, 'edit');
      return;
    }
    // 删除
    if (code === 'delete') {
      // const { rows } = callBackModel;
      // 调用删除服务，删除勾选数据
      return;
    }
    // 查看
    if (code === 'view') {
      const { rows } = callBackModel;
      openUpdateDictModal(rows, 'view');
      return;
    }
  }

  /**
   * 表格勾选回调函数
   * @param {*} rows 表格选中数据集合
   */
  const onSelectRow = (keys: React.Key[], rows: DictItem[]) => {
    setSelectedRowKeys(keys);
    setSelectedRows(rows);
  };

  /**
   * 页码改变的回调，参数是改变后的页码及每页条数
   * @param page 改变后的页码，上送服务器端
   * @param pageSize 每页数据条数
   */
  const onPageNumAndSizeChange = (page: number, pageSize: number) => {
    console.log('onPageNumAndSizeChange', page, pageSize);
    // const { pageSize } = state;
    // if (pageSize === pageSizeEx) {
    //   console.log('每页数据条目无变化，无需通讯');
    //   return;
    // }
    // fetchAllDict(page, pageSize);
    setPageSize(pageSize);
    fetchAllDict(page, pageSize, queryParam);
  };

  const code = 'dict-list';
  const { dictList, loading, total, addLoading, updateLoading, editFlagData, statusData } = props;
  // console.log(dicList);
  // console.log(pageSize);
  const rowKey = (record: DictItem) => record.dictId;

  return (
    <PageContainer>
      <ProCard title="系统字典查询" headerBordered>
        <DictQueryForm
          colon={false}
          loading={loading}
          onSubmit={handleSubmitEx}
          onReset={handleReset}
        />
        <AGrid
          code={code}
          btnCallBack={handleBtnCallBack}
          columns={columns}
          rowKey={rowKey}
          pkField='dictId'
          dataSource={dictList}
          total={total}
          loading={loading}
          onSelectRow={onSelectRow}
          onPageNumAndSizeChange={onPageNumAndSizeChange}
          actionColumnFixed={'right'}
        />
      </ProCard>
      {
        !addModalVisible ? null :
        <AddDictModal
          editFlagData={editFlagData}
          statusData={statusData}
          colon={false}
          modalTitle='新增字典项'
          modalWidth={1000}
          modalVisible={addModalVisible}
          loading={addLoading}
          formData={dictFormData}
          onHandlerOK={handleAddModalOk}
          onHandlerCancel={handleAddModalCancel}
        />
      }
      {
        !updateModalVisible ? null :
        <UpdateDictModal
          editFlagData={editFlagData}
          statusData={statusData}
          colon={false}
          modalTitle=''
          modalWidth={1000}
          modalVisible={updateModalVisible}
          flag={flag}
          loading={updateLoading}
          formData={dictFormData}
          onHandlerOK={handleUpdateModalOk}
          onHandlerCancel={handleUpdateModalCancel}
        />
      }
    </PageContainer>
  );
}

export default connect(({ dicts: { rows, ...res }, loading }: ConnectState) => ({
  ...res,
  dictList: rows,
  loading: loading.effects['dicts/fetchAllDict'],
  addLoading: loading.effects['dicts/addDict'],
  updateLoading: loading.effects['dicts/updateDict'],
}))(DictList);